/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.bpmn.deployer;

import com.je.bpm.engine.impl.bpmn.parser.BpmnParse;
import com.je.bpm.engine.impl.bpmn.parser.BpmnParser;
import com.je.bpm.engine.impl.cmd.DeploymentSettings;
import com.je.bpm.engine.impl.persistence.entity.DeploymentEntity;
import com.je.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import com.je.bpm.engine.impl.persistence.entity.ResourceEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ParsedDeploymentBuilder {

    private static final Logger log = LoggerFactory.getLogger(ParsedDeploymentBuilder.class);

    protected DeploymentEntity deployment;
    protected BpmnParser bpmnParser;
    protected Map<String, Object> deploymentSettings;

    public ParsedDeploymentBuilder(DeploymentEntity deployment,
                                   BpmnParser bpmnParser, Map<String, Object> deploymentSettings) {
        this.deployment = deployment;
        this.bpmnParser = bpmnParser;
        this.deploymentSettings = deploymentSettings;
    }

    public ParsedDeployment build() {
        List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
        Map<ProcessDefinitionEntity, BpmnParse> processDefinitionsToBpmnParseMap = new LinkedHashMap<ProcessDefinitionEntity, BpmnParse>();
        Map<ProcessDefinitionEntity, ResourceEntity> processDefinitionsToResourceMap = new LinkedHashMap<ProcessDefinitionEntity, ResourceEntity>();
        for (ResourceEntity resource : deployment.getResources().values()) {
            if (isBpmnResource(resource.getName())) {
                log.debug("Processing BPMN resource {}", resource.getName());
                BpmnParse parse = createBpmnParseFromResource(resource);
                for (ProcessDefinitionEntity processDefinition : parse.getProcessDefinitions()) {
                    processDefinitions.add(processDefinition);
                    processDefinitionsToBpmnParseMap.put(processDefinition, parse);
                    processDefinitionsToResourceMap.put(processDefinition, resource);
                }
            }
        }

        return new ParsedDeployment(deployment, processDefinitions, processDefinitionsToBpmnParseMap, processDefinitionsToResourceMap);
    }

    protected BpmnParse createBpmnParseFromResource(ResourceEntity resource) {
        String resourceName = resource.getName();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(resource.getBytes());

        BpmnParse bpmnParse = bpmnParser.createParse()
                .sourceInputStream(inputStream)
                .setSourceSystemId(resourceName)
                .deployment(deployment)
                .name(resourceName);

        if (deploymentSettings != null) {

            // Schema validation if needed
            if (deploymentSettings.containsKey(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED)) {
                bpmnParse.setValidateSchema((Boolean) deploymentSettings.get(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED));
            }

            // Process validation if needed
            if (deploymentSettings.containsKey(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED)) {
                bpmnParse.setValidateProcess((Boolean) deploymentSettings.get(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED));
            }

        } else {
            // On redeploy, we assume it is validated at the first deploy
            bpmnParse.setValidateSchema(false);
            bpmnParse.setValidateProcess(false);
        }

        bpmnParse.execute();
        return bpmnParse;
    }

    protected boolean isBpmnResource(String resourceName) {
        for (String suffix : ResourceNameUtil.BPMN_RESOURCE_SUFFIXES) {
            if (resourceName.endsWith(suffix)) {
                return true;
            }
        }

        return false;
    }

}
